<template>
  <div>
    <header>
      标题: <input type="text" v-model="title" />价格:
      <input type="text" v-model="price" />
      <button @click="add">添加</button>
    </header>
    <table>
      <thead>
        <th>标题</th>
        <th>价格</th>
        <th>时间</th>
        <th>操作</th>
      </thead>
      <tbody>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ item.title }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.time | fomterTime }}</td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      title: "",
      price: null,
      list: [], // 存放表格数据的
    };
  },
  watch: {
    // title(newVal,oldval){ 只能监听数字或者字符串的变化
    //     console.log(newVal);
    //     console.log(oldval);
    //     console.log('eggegr');
    // }
    list: { // 对数组进行深度监听
      handler() {
         localStorage.setItem("list", JSON.stringify(this.list));
      },
      deep: true, // 是否开启深度监听 true 表示开启 ，默认是false
    },
  },
  filters:{ // 过滤器 
     fomterTime(val){
        // console.log(val);
        let date = new Date(val);
        let year = date.getFullYear();
        // console.log(year);
        let moth = date.getMonth()+1;
        // console.log(moth);
        let day = date.getDate();

        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        return `${year}-${moth}-${day} ${h}:${m}:${s}`
     }
  },
  created() {
    // 如果JSON.parse(localStorage.getItem('list')) 的值为 null 就把 [] 赋值给this.list
    this.list = JSON.parse(localStorage.getItem("list")) || [];
  },
  methods: {
    add() {
      // 添加的事件
      // 点击添加的函数
      if (this.title && this.price) {
        this.list.push({
          title: this.title,
          price: this.price,
          time: new Date(),
        });
        // console.log(this.list);
      } else {
        alert("请输入书名或者价格");
      }
    },
    del(i) {
      // 删除的事件
      this.list.splice(i, 1);
    },
  },
};
</script>
<style lang="scss" scoped>
table {
  width: 600px;
  margin: 10px auto;
}
</style>